package org.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author 别人
 */
public class JWTUtils {
    // 过期时间(毫秒)
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
    // 用户的密码(假设)
    private static final String secret = "43dcbc5b-8776-429e-b122-3cae6bd97020";

    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @return 是否正确
     */
    public static boolean verify(String token) {
        try {
            // 根据密码生成JWT校验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 校验Token
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 签发token
     *
     * @param id
     * @return 加密的token
     */
    public static String sign(Long id) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            //附带username信息
            return JWT.create().withClaim("id", id).withExpiresAt(date).sign(algorithm);
        } catch (Exception exception) {
            return null;
        }
    }
}
